<template>
  <div>
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="selectATit"
          :param="param"
          :tname="tname"
          :leftTreeParentId="leftTreeParentId"
          :searchWord="searchWord"
          @getChartData="getChartData"
        ></ChooseScreen>
        <div class="right-tools">
          <span
            @click="handleShowContrastive"
            v-if="
              tname == '主要发明人排名' ||
                tname == '主要申请人排名' ||
                tname == '主要申请人排名对比分析' ||
                tname == '主要发明人排名对比分析'
            "
            >对比分析</span
          >
        </div>
      </template>
      <template slot="chart">
        <ChartB
          v-if="datatype !== -1 && !loading"
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
          @domRef="getDomRef"
          @contrastiveData="getContrastiveData"
        />
        <div v-if="loading" class="chart-loading-box">
          <loading1 :emptyText="emptyText" />
        </div>
      </template>
      <template slot="type">
        <!-- <i class="icon el-icon-download" @click="exportData">导出数据</i> -->
        <i class="icon el-icon-download" @click="downloadImg">保存图片</i>
        <i class="icon el-icon-full-screen" @click="handleFullScreen"
          >&nbsp;全屏</i
        >
      </template>
    </c-slot>

    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit" :class="[tname == '技术领域排名' ? 'jslypm' : '']">
          <p style="flex: none; width: 30px"></p>
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
          :class="[tname == '技术领域排名' ? 'jslypm' : '']"
        >
          <p style="flex: none; width: 30px">
            <el-checkbox
              v-model="checkList[index]"
              :key="index"
              @change="handleChangeCheck"
              >&nbsp;</el-checkbox
            >
          </p>
          <p>{{ index + 1 }}</p>
          <p
            v-for="(ite, j) in item"
            :key="j"
            :class="[j == 0 && tname == '学者分析' ? 'pointer' : '']"
          >
            <span
              v-if="!tableData.inputRefs[index][j]"
              @click="handleClick(ite)"
              >{{ ite }}</span
            >
            <span v-else>
              <el-input
                v-model="tableData._content[index][j]"
                placeholder=""
                size="mini"
                :style="{
                  'min-width':
                    tableData._content[index][j].length >= 10
                      ? '230px'
                      : '100px',
                }"
              ></el-input>
            </span>
            <span class="tools-box">
              <!-- 修改 -->
              <i
                v-if="!tableData.inputRefs[index][j]"
                class="tools-btn el-icon-edit"
                @click="handleShowInp(index, j)"
              ></i>
              <!-- 保存 -->
              <i
                v-if="tableData.inputRefs[index][j]"
                class="tools-btn el-icon-check"
                @click="handleUpdateIte(index, j)"
              ></i>
              <!-- 取消 -->
              <i
                v-if="tableData.inputRefs[index][j]"
                class="tools-btn el-icon-close"
                @click="handleShowInp(index, j)"
              ></i>
            </span>
          </p>
        </li>
      </ul>
    </div>

    <!-- 对比分析 -->
    <Contrastive ref="contrastive" />
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartB from "../charts/ChartB";
import { refactor, downloadChartImg, transCNCountry } from "@/utils/utils";
import base64 from "@/utils/base64.js";
import Contrastive from "../Contrastive";
import ChooseScreen from "./chooseScreen.vue";
import { handlesShowtopsize } from "@/utils/utils";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object,
    },
    dcData: {
      type: Object,
    },
  },
  components: {
    CSlot,
    ChartB,
    Contrastive,
    ChooseScreen,
  },
  data() {
    return {
      searchTxt: "",
      loading: true,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      charttype: -1, // 图表类型
      selectATit: "", // 筛选条件B，动态
      timeType: "isd", // 设置时间筛选类型
      chartId: "", // 图表id名称
      datatype: -1, // 图表数据类型
      chartData: [],
      chartType: "line",
      dom: {},
      domRef: null, // 记录图表dom对象，用于全屏
      copyData: [],
      ipcnamearr: [],
      tableData: {
        tit: [],
        content: [],
        content_ipcname: [],
        _content: [], // 存储修改content值
        inputRefs: [], // 记录修改展示的input的值
      },
      originTableData: [], // 表格数据--全部字段
      checkList: [], // 多选框勾选数据
      yearArr: [],
      contrastiveData: [], // 对比分析的数据
      emptyText: "数据加载中...",
      dbid: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: "",
      msq: "",
      oldRes: "", // 用于数据对比
      leftTreeParentId: 0,
    };
  },
  computed: {
    ...mapState(["searchWord"]),
  },
  watch: {
    // chartTempl() {
    //   this.init();
    // },
    dcData() {
      this.init();
    },
  },
  mounted() {
    this.dbid = String(this.$route.query.type);
    // this.init();
  },
  methods: {
    init() {
      this.leftTreeParentId = this.chartTempl.parentId;
      this.tname = this.chartTempl.tname;
      this.param = this.chartTempl.tdata.param;
      this.charttype = this.chartTempl.tdata.charttype;
      this.chartId = "chart" + this.chartTempl.id;
      this.datatype = this.chartTempl.tdata.datatype;
      this.timeType = this.chartTempl.tdata.datefield;
      this.datefieldformat = this.chartTempl.tdata.datefieldformat;
      this.datefieldformatTxt = this.datefieldformat == 1 ? "-01-01" : "";
      this.checkList = [];
      if (this.dcData && this.dcData.chartData) {
        let data = JSON.parse(JSON.stringify(this.dcData.chartData));
        this.originTableData = JSON.parse(
          JSON.stringify(this.dcData.chartData)
        );
        // console.log("originTableData",this.originTableData);
        data.sort(function(a, b) {
          return Number(a.term) - Number(b.term);
        });
        if (handlesShowtopsize(this.tname)) {
          data = data.slice(0, 10); //特定情况下 默认展示前10
        }
        this.loading = false;
        data.forEach((v) => {
          v.key = transCNCountry(v.key);
        });
        this.copyData = JSON.parse(JSON.stringify(data));
        refactor({
          type: this.dcData.datatype, // 根据后台返回的datatype，判断数据解析格式
          data,
          callback: (refactor) => {
            this.chartData = [refactor] || [];
          },
        });
      } else {
        this.emptyText = "数据加载中...";
      }
      this.handleParams();
      this.handleTable();
    },
    // 处理下方table数据展示，根据分析类型，展示不同的表头
    handleTable() {
      // console.log('----',this.tname)
      switch (this.tname) {
        case "申请人趋势分析":
          this.tableData.tit = ["索引", "年份", "申请人数量"];
          break;
        case "趋势分析":
          this.tableData.tit = ["索引", "年份", "论文数"];
          break;
        case "学者分析":
          this.tableData.tit = ["索引", "专家姓名", "学者机构", "论文数"];
          break;

        case "发明人趋势分析":
          this.tableData.tit = ["索引", "年份", "发明人数量"];
          break;

        case "全球申请排名":
          this.tableData.tit = ["索引", "国家", "专利申请量"];
          break;
        case "全国申请排名":
          this.tableData.tit = ["索引", "省份", "专利申请量"];
          break;

        case "主要申请人排名":
          this.tableData.tit = ["索引", "主要申请人", "申请人数量"];
          break;

        case "申请人申请趋势分析":
          this.tableData.tit = ["索引", "申请人申请", "申请人数量"];
          break;

        case "主要发明人排名":
          this.tableData.tit = ["索引", "主要发明人", "发明人数量"];
          break;
        case "发明人申请趋势分析":
          this.tableData.tit = ["索引", "发明人申请", "发明人数量"];
          break;
        case "技术领域排名":
          this.tableData.tit = ["索引", "IPC", "IPC名称", "专利数量"];
          break;
        default:
      }
      this.tableData.content = [];
      this.tableData._content = [];
      this.tableData.inputRefs = [];
      this.checkList = [];
      if (this.tname == "学者分析") {
        this.copyData.map((it, i) => {
          this.tableData.content.push([
            it.key,
            it.org_zh || it.org,
            it.doc_count,
          ]);
          this.tableData._content.push([
            it.key,
            it.org_zh || it.org,
            it.doc_count,
          ]);
          this.checkList.push(true);
          // 记录inputRefs
          let arr = this.tableData._content[0];
          let boo = [];
          arr.map((v, k) => {
            boo.push(false);
          });
          this.tableData.inputRefs.push(boo);
        });
        return;
      }
      this.chartData[0] &&
        this.chartData[0].xArr.map((it, i) => {
          this.ipcnamearr.push(it);
          let y = String(this.chartData[0].yArr[i]);
          this.tableData.content.push([it, y]);
          this.tableData._content.push([it, y]);
          this.checkList.push(true);
          // 记录inputRefs
          let arr = this.tableData._content[0];
          let boo = [];
          arr.map((v, k) => {
            boo.push(false);
          });
          this.tableData.inputRefs.push(boo);
        });
      if (this.tname == "技术领域排名") {
        this.getipcname(this.ipcnamearr);
      }
    },
    //技术领域排名 模块下 需要调用接口将ipc转为中文，追加中文展示
    getipcname(params) {
      if (params.length == 0) {
        return;
      }
      this.$post(this.$Url.search.searchipcname, { ipcm: params }).then(
        (res) => {
          // console.log("res", res.data,this.tableData.content);
          if (!res.data) {
            return;
          }
          let newRes = JSON.stringify(res.data);
          // 迫不得已，后续再优化，本接口会调用多次
          if (this.oldRes == newRes) {
            return;
          } else {
            this.oldRes = newRes;
          }
          let tc = JSON.parse(JSON.stringify(this.tableData.content));
          // return;
          for (let key in res.data) {
            let index = tc.findIndex((it) => it[0] == key);
            let ipc = tc[index][0];
            let ipcname = res.data[key];
            let num = tc[index][1];
            // console.log("num",num);
            tc[index] = [ipc, ipcname, num];
            // this.$set(this.tableData.content, index, [ipc, ipcname, num]);
          }
          // console.log("tc", tc);
          this.tableData.content = tc;
          // console.log("this.tableData.content",this.tableData.content);
        }
      );
    },
    // 修改表格文字内容
    handleUpdateIte(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请勾选后再进行修改",
        });
        return;
      }
      this.$set(
        this.tableData.content[index],
        j,
        this.tableData._content[index][j]
      );
      this.handleShowInp(index, j);
      // 重新设置chartData数据
      let chartData = JSON.parse(JSON.stringify(this.chartData));
      if (this.tname == "学者分析") {
        if (j == 0) {
          chartData[0]["xArr"][index] = this.tableData.content[index][j];
        } else if (j == 2) {
          chartData[0]["yArr"][index] = this.tableData.content[index][j];
        }
      } else {
        if (j == 0) {
          chartData[0]["xArr"][index] = this.tableData.content[index][j];
        } else if (j == 1) {
          chartData[0]["yArr"][index] = this.tableData.content[index][j];
        }
      }
      this.chartData = chartData;
    },
    // 显隐修改表格文字input框
    handleShowInp(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请选勾选后再进行修改",
        });
        return;
      }
      if (this.tableData.inputRefs[index][j] === true) {
        this.$set(this.tableData.inputRefs[index], j, false);
      } else {
        this.$set(this.tableData.inputRefs[index], j, true);
      }
    },
    // 勾选
    handleChangeCheck() {
      let chartData = JSON.parse(JSON.stringify(this.chartData));
      this.checkList.forEach((v, index) => {
        if (v === true) {
          chartData[0]["xArr"][index] = this.tableData._content[index][0];
          chartData[0]["yArr"][index] = this.tableData._content[index][1];
        } else {
          chartData[0]["xArr"][index] = null;
          chartData[0]["yArr"][index] = null;
        }
      });
      chartData[0]["xArr"] = chartData[0]["xArr"].filter((v) => v !== null);
      chartData[0]["yArr"] = chartData[0]["yArr"].filter((v) => v !== null);
      this.chartData = chartData;
    },
    // 论文分析--学者分析：点击跳转人才画像
    handleClick(ite) {
      // console.log(ite);
      if (this.tname == "学者分析") {
        this.originTableData.find((v) => {
          if (v.key == ite || v.name == ite) {
            this.$nextTick(() => {
              let routerUrl = this.$router.resolve({
                name: "PD",
                query: {
                  expertId: v.expert_id,
                },
              });
              window.open(routerUrl.href, "_blank");
            });
          }
        });
      }
    },
    // 拼装sq 给对比分析使用
    handleParams() {
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=2012${this.datefieldformatTxt} AND ${this.timeType}<=2022${this.datefieldformatTxt}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq;
      }
      this.msq = sq;
    },
    getChartData(Params) {
      this.handleTable();
      if (this.cancel !== null) {
        this.cancel();
      }
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=${Params.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${Params.endYear}${this.datefieldformatTxt}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq;
      }
      if (this.tname == "主要申请人排名" && Params.range) {
        sq += Params.range;
      }
      this.msq = sq;
      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = [];
      this.tableData = {
        tit: [],
        content: [],
        _content: [],
        inputRefs: [],
      };
      //触发search接口
      // this.chartTempl.tdata.param.aggs[0]['size'] = Params.size
      let waggs = this.chartTempl.tdata.param.aggs;
      waggs[0]["size"] = Params.size;
      if (waggs[0]["aggs"]) {
        waggs[0]["aggs"][0]["size"] = Params.size;
      }
      let params = {
        aggs: waggs,
        dbid: this.dbid,
        eSearch: sq,
        ipi: 1,
        ips: 0,
        rSearch: "",
        smartSearch: "",
        sort: [],
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      let familyFlag = localStorage.getItem("familyFlag") || false;
      if (familyFlag ==1 ) {
        params["familyFlag"] = true; // 同族合并
        params["tzzlhb"] = false; // 同专利合并
      } else if (familyFlag ==2) {
        params["familyFlag"] = false; // 同族合并
        params["tzzlhb"] = true; // 同专利合并
      }
      // console.log(99, this.chartId)
      if (this.chartId == "chart201000" || this.chartId == "chart202000") {
        params["other"] = true;
      }
      if (this.chartId == "chart301000") {
        params["translate"] = true;
      }
      let ths = this;
      this.$post(this.$Url.search.commonSearch, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
        }),
      })
        .then((res) => {
          let data = JSON.parse(JSON.stringify(res.data.chartData));
          this.$store.commit("setTotalTxt", res.data.total);
          this.originTableData = JSON.parse(
            JSON.stringify(this.dcData.chartData)
          );
          // console.log("originTableData",this.originTableData);
          data.sort(function(a, b) {
            return Number(a.term) - Number(b.term);
          });
          if (handlesShowtopsize(this.tname)) {
            data = data.slice(0, Params.size); //特定情况下 默认展示前Params.size
          }
          this.loading = false;
          data.forEach((v) => {
            v.key = transCNCountry(v.key);
          });
          refactor({
            type: this.dcData.datatype, // 根据后台返回的datatype，判断数据解析格式
            data,
            callback: (refactor) => {
              this.chartData = [refactor] || [];
              this.handleTable();
            },
          });
        })
        .catch((err) => {
          this.emptyText = "暂无数据1";
          this.loading = false;
        });
    },
    getDomRef(dom) {
      this.domRef = dom;
    },
    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    // 全屏
    handleFullScreen() {
      let element = this.domRef;
      if (!element) {
        return;
      }
      // 全屏查看
      if (element.requestFullScreen) {
        // HTML W3C 提议
        element.requestFullScreen();
      } else if (element.msRequestFullscreen) {
        // IE11
        element.msRequestFullScreen();
      } else if (element.webkitRequestFullScreen) {
        // Webkit
        element.webkitRequestFullScreen();
      } else if (element.mozRequestFullScreen) {
        // Firefox
        element.mozRequestFullScreen();
      }
      // 退出全屏
      if (element.requestFullScreen) {
        document.exitFullscreen();
      } else if (element.msRequestFullScreen) {
        document.msExitFullscreen();
      } else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
      } else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
      }
    },
    // 保存图片
    downloadImg() {
      downloadChartImg(this.dom);
    },
    // 对比分析
    getContrastiveData(data) {
      this.contrastiveData = data;
    },
    handleShowContrastive() {
      if (this.contrastiveData.length <= 0) {
        this.$message.warning("请至少选择一项数据！");
        return;
      }
      this.$refs.contrastive.init(
        this.contrastiveData,
        this.chartTempl,
        this.dbid,
        this.msq
      );
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws = XLSX.utils.aoa_to_sheet(
        aoa
      ); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    },
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      // this.loading = false;
      this.cancel();
    }
  },
};
</script>

<style lang="scss">
.chart-tab .chart-tab-ul li {
  &.jslypm {
    p {
      &:nth-of-type(2) {
        flex: 0.3 !important;
      }
      &:nth-of-type(3) {
        flex: 0.5 !important;
      }
      &:nth-of-type(5) {
        flex: 0.5 !important;
      }
    }
  }
}
.pointer {
  cursor: pointer;
}
</style>
